/**
 * 用户登录
 */
import query from '../../untils/mysql';
import { Tip } from '../../untils/untils';
import { check, validationResult } from 'express-validator';
import { testing } from '../../untils/validator';
import jwt from "jsonwebtoken";
import { jwtSecretKey } from "../../config/token";

const validator = [
    check('phone').custom((val) => {
        if (!testing.isPhone(val)) {
            throw new Error('手机号格式有误');
        } else {
            return val
        }
    }),
    check('password').isLength({ min: 6, max: 16 }).withMessage('密码长度6-16位之间')
]
const POST = async (req: any, res: any, next: any) => {
    try {
        const { phone, password } = req.body;
        var errors = validationResult(req);
        if (!errors.isEmpty()) {
            return Tip.tipError(res, errors.array()[0].msg);
        }
        const resPhone = await query(`select phone from user where phone = '${phone}'`);
        if (resPhone.length === 0) {
            return Tip.tipError(res, '当前账号未注册');
        }
        let data = await query(`select * from user where phone = '${phone}' and password = '${password}'`);
        if (data.length === 0) {
            return Tip.tipError(res, '账户或密码不对');
        }
        let user = {
            userId: data[0].id,
            ...data[0]
        }
        delete user.password;
        const tokenStr = jwt.sign(user, jwtSecretKey, {
            expiresIn: '10h', // token 有效期为 10 个小时
        })
        return Tip.tipSuccess(res, '登录成功', {
            ...user,
            token: 'Bearer ' + tokenStr,
        });
    } catch (error: any) {
        Tip.tipError500(res, error)
    }
}

export {
    POST,
    validator
}